package com.yamaikeji.plan.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yamaikeji.common.core.controller.BaseController;
import com.yamaikeji.common.core.domain.AjaxResult;
import com.yamaikeji.common.utils.StringUtils;
import com.yamaikeji.framework.util.RedisUtil;
import com.yamaikeji.plan.aop.CheckLogin;
import com.yamaikeji.plan.dto.ResWeatherDTO;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 基础Controller
 * 
 * @author yamaikeji
 * @date 2023-10-03
 */
@RestController
@RequestMapping("/api/plan/base")
public class PlanBaseController extends BaseController {

    @Resource
    private RedisUtil redisUtil;

    private static String gdKey = "b2499bbb35721fba732ac10a00cce811";
    private static String ipApi = "https://restapi.amap.com/v3/ip?ip=%s&output=json&key=" + gdKey;
    private static String weatherApi = "https://restapi.amap.com/v3/weather/weatherInfo?city=%s&key=" + gdKey;

    /**
     * 查询任务列表
     */
    @CheckLogin
    @PostMapping("/getWeather")
    public AjaxResult getWeather(HttpServletRequest request) {
        ResWeatherDTO resWeatherDTO = new ResWeatherDTO();
        String requestIp = this.getRequestIp(request);
        if (StringUtils.isEmpty(requestIp)) {
            return AjaxResult.success(resWeatherDTO);
        }
        try {
            String adcode;
            OkHttpClient httpClient = new OkHttpClient();
            Request getRequest = new Request.Builder()
                    .url(String.format(ipApi, requestIp))
                    .get()
                    .build();
            Response response = httpClient.newCall(getRequest).execute();
            if (response.isSuccessful()) {
                String responseData = response.body().string();
                JSONObject jSONObject = JSON.parseObject(responseData);
                adcode = (String) jSONObject.get("adcode");
                if (StringUtils.isEmpty(adcode)) {
                    return AjaxResult.success(resWeatherDTO);
                }
                System.out.println(adcode);
            } else {
                logger.error("ipApi, code: " + response.code());
                return AjaxResult.success(resWeatherDTO);
            }

            getRequest = new Request.Builder()
                    .url(String.format(weatherApi, adcode))
                    .get()
                    .build();
            response = httpClient.newCall(getRequest).execute();
            if (response.isSuccessful()) {
                String responseData = response.body().string();
                JSONObject jSONObject = JSON.parseObject(responseData);
                JSONArray lives = (JSONArray)jSONObject.get("lives");
                JSONObject live = (JSONObject)lives.get(0);
                if (live == null) {
                    return AjaxResult.success(resWeatherDTO);
                }
                String weather = (String)live.get("weather");
                String temperature = (String)live.get("temperature");
                resWeatherDTO.setWeather(weather);
                resWeatherDTO.setTemperature(temperature + "℃");
            } else {
                logger.error("weatherApi, code: " + response.code());
            }
        } catch (Exception e) {
            logger.error("gdApi: " + e.getMessage());
            return AjaxResult.success(resWeatherDTO);
        }
        return AjaxResult.success(resWeatherDTO);
    }

    private String getRequestIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }
}
